import React from 'react'
import './style.scss'
import { Form, Input, Button, message as antdMessage } from 'antd'
import axios from 'axios'
import { useNavigate } from 'react-router-dom'
interface LoginState {
  username: string
  password: string
}

const Index: React.FC = () => {
  const navigate = useNavigate()
  const onFinish = (data: LoginState) => {
    // 发送请求
    axios.post('/api/login', data).then((resp) => {
      const { code, data, message } = resp.data
      if(code === 200) {
        antdMessage.success(message);
        // 跳转首页
        navigate('/')
        // 存储
        localStorage.setItem('token', data.token)
        localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
      } else {
        antdMessage.error(message)
      }
    })
  }
  return (
    <div className='login'>
      <div className="box">
        <Form initialValues={{
          username: '13111111111',
          password: '123456'
        }} wrapperCol={{ span: 20 }} labelCol={{ span: 4 }} onFinish={onFinish}>
          <Form.Item wrapperCol={{ span: 24 }}>
            <h2 style={{ textAlign: 'center' }}>用户登录</h2>
          </Form.Item>
          <Form.Item label="用户名" name="username" rules={[
            {
              required: true,
              message: '用户名不可以为空！'
            },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '手机号格式不正确'
            }
          ]}>
            <Input placeholder='请输入手机号'></Input>
          </Form.Item>
          <Form.Item label="密码" name="password" rules={
            [
              {
                required: true,
                message: '密码不可以为空'
              },
              {
                pattern: /^\w{6,12}$/,
                message: '密码必须有6-12位数字、字母、特殊字符组成'
              }
            ]
          }>
            <Input.Password></Input.Password>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button type="primary" block htmlType='submit'>登录</Button>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button type="primary" block>重置</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Index